<script setup lang='ts'>
import { useRoute } from 'vue-router';
import Avatar from '../../../components/avatar.vue';
import { reqGetAllMemberProjectById, reqRemoveMember } from '../../../apis/project';
import { ref } from 'vue';
import { watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import useUserStore from '../../../store/modules/user';
import { reqChangeMemberRoleById } from '../../../apis/project/index';
import useSettingStore from '../../../store/modules/setting';
import type { ProjectMember } from '../../../apis/project/type'

const useSetting = useSettingStore()
const useUser = useUserStore()
const memberDrawerVisible = defineModel('status')
const emit = defineEmits(['refresh'])
const $route = useRoute()
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0
})
const memberList = ref<ProjectMember[]>([])
const dialogVisible = ref(false)
const currentMember = ref<ProjectMember>()

const getMemberList = async () => {
  const res = await reqGetAllMemberProjectById(Number($route.params.id))
  if (res.code === 200) {
    memberList.value = res.data
    pageData.value.total = res.data.length
  }
}

const handleMemberInfo = (item: any) => {
  currentMember.value = JSON.parse(JSON.stringify(item))
  dialogVisible.value = true
}


const haveRight = () => {
  const admin = memberList.value.filter((item: ProjectMember) => item.projectRole === 'admin')
  return admin.find((item: ProjectMember) => item.id === useUser.id) || useUser.role === 'admin'
}

const isCreater = (id = useUser.id) => {
  const creater = memberList.value.filter((item: ProjectMember) => item.projectRole === null)
  return creater.find((item: ProjectMember) => item.id === id)
}

const handlerChangeMemberRole = async () => {
  if (!currentMember.value) return;
  try {
    const res = await reqChangeMemberRoleById(
      Number($route.params.id),
      currentMember.value.id,
      currentMember.value.projectRole as string
    );

    if (res.code === 200) {
      ElMessage.success('角色更新成功');
      dialogVisible.value = false;
      getMemberList();
    } else {
      ElMessage.error(res.msg || '角色更新失败');
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络');
  }
}

const handlerRemoveMember = (id: number, username: string) => {
  ElMessageBox.confirm(`确认要将成员 ${username}移出空间吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqRemoveMember(Number($route.params.id), id)
    if (res.code === 200) {
      ElMessage.success('移出成功')
      getMemberList()
      emit('refresh')
    }
  })
}

const mapRoleToText = (role: string) => {
  const roleMap: Record<string, string> = {
    null: '创建人',
    'admin': '管理员',
    'developer': '开发者',
    'tester': '测试'
  }
  return roleMap[role]
}

watch(memberDrawerVisible, (newVal) => {
  if (newVal) {
    getMemberList()
  }
})
</script>


<template>
  <el-drawer v-model="memberDrawerVisible" direction="rtl" size="20%">
    <template #header>
      <div class="header">
        <p :class="{ 'dark-mode': !useSetting.isLight }">项目成员({{ pageData.total }})</p>
        <el-divider />
      </div>
    </template>
    <div class="member_item" v-for="item in memberList" :key="item.id">
      <div class="item_left">
        <Avatar :name="item.username"></Avatar>
      </div>
      <div class="item_right">
        <div class="right_top">
          <div class="inner_right">
            <p class="name">{{ item.username }}</p>
            <el-tag v-if="item.projectRole === null" type="danger">创建人</el-tag>
            <el-tag v-else-if="item.projectRole === 'admin'" type="success">管理员</el-tag>
            <el-tag v-else-if="item.projectRole === 'developer'" type="primary">开发者</el-tag>
            <el-tag v-else-if="item.projectRole === 'tester'" type="primary">测试</el-tag>
          </div>
          <el-dropdown>
            <el-button size="small" icon="MoreFilled" circle></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="House" @click="handleMemberInfo(item)">成员信息</el-dropdown-item>
                <el-dropdown-item divided icon="SwitchButton" v-if="haveRight() || isCreater()"
                  @click="handlerRemoveMember(item.id, item.username)">移出空间</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="right_bottom">
          <p>{{ mapRoleToText(item.projectRole as string) }}</p>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" width="500px" v-if="currentMember">
      <template #header>
        <div class="header">
          <p>成员信息</p>
        </div>
      </template>
      <template #default>
        <div class="avatar">
          <Avatar :name="currentMember.username" class="dialog_avatar" :size="80"></Avatar>
          <p class="dialog_name">{{ currentMember.username }}</p>
        </div>
        <el-form label-width="100px">
          <el-form-item label="成员ID:">
            <span>{{ currentMember.id }}</span>
          </el-form-item>
          <el-form-item label="成员昵称:">
            <span>{{ currentMember.username }}</span>
          </el-form-item>
          <el-form-item label="邮箱地址:">
            <span>{{ currentMember.email }}</span>
          </el-form-item>
          <el-form-item label="角色:">
            <el-tag type="danger" v-if="isCreater(currentMember.id)">创建人</el-tag>
            <el-radio-group v-model="currentMember.projectRole" v-else-if="haveRight() || isCreater()">
              <el-radio value="admin" size="large"
                style="display: flex; align-items: center; height: 32px">管理员</el-radio>
              <el-radio value="developer" size="large"
                style="display: flex; align-items: center; height: 32px">开发者</el-radio>
              <el-radio value="tester" size="large"
                style="display: flex; align-items: center; height: 32px">测试</el-radio>
            </el-radio-group>
            <el-tag v-else :type="currentMember.projectRole === 'admin' ? 'success' : 'primary'">{{
              mapRoleToText(currentMember.projectRole as string) }}</el-tag>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer" v-if="haveRight() || isCreater()">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlerChangeMemberRole()">
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>


</template>


<style scoped lang='scss'>
.header {
  font-size: 22px;
  font-weight: 400;

  .dark-mode {
    color: #fff;
  }
}

.member_item {
  width: 100%;
  display: flex;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
  cursor: pointer;

  .item_right {
    width: 100%;
    margin-left: 10px;

    .right_top {
      position: relative;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .inner_right {
        display: flex;
        align-items: center;

        .name {
          font-size: 14px;
          margin-right: 5px;
        }
      }


      :deep(el-button) {
        position: absolute;
        top: 0;
        right: 0;
      }
    }

    .right_bottom {
      font-size: 14px;
      margin-top: 5px;
      color: #888;
    }
  }

  &:hover {
    background-color: var(--el-fill-color-light); // 使用Element Plus的主题色
  }


}

.avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  text-align: center;

  .dialog_avatar {
    margin-bottom: 10px;
    border: none;
  }

  .dialog_name {
    font-size: 22px;

  }
}
</style>